package com.web709.common;

import com.alibaba.fastjson.JSON;
import com.web709.util.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(urlPatterns = "",asyncSupported = true)
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURL().toString();
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/swagger-ui") || requestURI.startsWith("/v3") || requestURI.startsWith("/webjars")|| requestURI.startsWith("/swagger-resources")) {
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(request, response);
            return;
        }
        if (url.contains("login") || url.contains("sendMsg") || url.contains("register") || url.contains("static")|| url.contains("doc.html")) {
            filterChain.doFilter(request, response);
            return;
        }
        String jwt = request.getHeader("token");
        if (jwt == null || jwt.equals("")) {
            R r = R.error("NOTLOGIN");
            String json = JSON.toJSONString(r);
            response.getWriter().write(json);
            return;
        }
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            R r = R.error("NOTLOGIN");
            String json = JSON.toJSONString(r);
            response.getWriter().write(json);
            return;
        }
        filterChain.doFilter(request, response);
    }
}